#!/bin/bash

die() { echo "$0: $@" && exit 1 ;}

usage() {
	cat <<-USAGE
		Usage: touchpad -[edt]
		Enable or disable the touchpad.

		-e 	Enbales the touchpad
		-d 	Disables the touchpad
		-t 	Toggles the touchpad state
		-h 	Prints this help message
	USAGE
	exit $1
}

# Helper function to get the ID for the touchpad
_get_touchpad_id() {
    local id=$(xinput | grep -F PS/2)
    id="$(echo ${id##*id=})"
    id="${id%% *}"
    echo $id
}

# Error handling
[[ -d /proc/acpi/button/lid/ ]] || die "system not a laptop"
command -v xinput &>/dev/null || die "xinput not found in system PATH"
ps -e | grep -Fq 'X' || die 'No X server running'


case "$1" in
	-e) action=enable ;;
	-d) action=disable ;;
	-t)
		# disabled
		if [[ "$(xinput | grep -F floating)" == *id=$TOUCHPADID* ]] ; then
			action=enable
		# enabled
		else action=disable
		fi
	;;
	-h) usage 0 ;;
	*) usage 1 ;;
esac
xinput $action $(_get_touchpad_id)
